import time
import sys
from alg import Solution
from gen import generate_test_words

def test_edit_distance():
    """
    测试编辑距离算法，并记录每个测试用例的运行时间，并将结果输出到test.txt文件
    """
    solution = Solution()
    test_cases = generate_test_words()
    
    # 创建并打开test.txt文件用于写入结果
    with open('test.txt', 'w', encoding='utf-8') as f:
        f.write("编辑距离算法性能测试\n")
        f.write("-" * 60 + "\n")
        f.write(f"{'测试用例':^10}{'描述':^20}{'编辑距离':^10}{'运行时间 (ms)':^15}\n")
        f.write("-" * 60 + "\n")
        
        total_time = 0
        
        for i, (word1, word2, desc) in enumerate(test_cases, 1):
            start_time = time.time()
            distance = solution.minDistance(word1, word2)
            end_time = time.time()
            
            execution_time = (end_time - start_time) * 1000  # 转换为毫秒
            total_time += execution_time
            
            f.write(f"{i:^10}{desc:^20}{distance:^10}{execution_time:.3f}ms\n")
            
            # 输出详细信息
            f.write(f"  word1 ({len(word1)} 字符): {word1[:30] + '...' if len(word1) > 30 else word1}\n")
            f.write(f"  word2 ({len(word2)} 字符): {word2[:30] + '...' if len(word2) > 30 else word2}\n")
            f.write("\n")
        
        f.write("-" * 60 + "\n")
        f.write(f"总测试用例: {len(test_cases)}\n")
        f.write(f"总运行时间: {total_time:.3f}ms\n")
        f.write(f"平均运行时间: {total_time / len(test_cases):.3f}ms\n")
    
    print(f"测试完成，结果已保存到test.txt文件中")

if __name__ == "__main__":
    test_edit_distance()